package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"

	"github.com/fatih/color"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	flag       int // current status
}

func NewClient(serverIp string, serverPort int) *Client {
	// create client
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
		flag:       999,
	}
	// connect to server
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		fmt.Println("net dail err:", err)
		return nil
	}
	client.conn = conn
	return client
}

func (client *Client) menu() bool {
	var flag int

	color.Cyan("\n=== 聊天系统菜单 ===")
	color.White("1. 群聊模式 💬")
	color.White("2. 私聊模式 👥")
	color.White("3. 修改用户名 ✏️")
	color.White("0. 退出系统 🚪")

	fmt.Scanln(&flag)
	if flag >= 0 && flag <= 3 {
		client.flag = flag
		return true
	} else {
		color.Red("请输入有效的选项 (0-3)")
		return false
	}
}

func (client *Client) Run() {
	for client.flag != 0 {
		for !client.menu() {
		}
		switch client.flag {
		case 1:
			// public chat
			client.PublicChat()
			break
		case 2:
			// private chat
			client.PrivateChat()
			break
		case 3:
			// update username
			client.UpdateName()
			break
		}
	}
}

func (client *Client) UpdateName() bool {
	color.Yellow("请输入新的用户名:")
	fmt.Scanln(&client.Name)

	sendMsg := "rename|" + client.Name + "\n"
	_, err := client.conn.Write([]byte(sendMsg))
	if err != nil {
		color.Red("发送失败: %v", err)
		return false
	}
	color.Green("用户名更新成功! ✨")
	return true
}

func (client *Client) SelectUsers() {
	sendMsg := "who\n"
	_, err := client.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("conn Write err:", err)
		return
	}
}

func (client *Client) PrivateChat() {
	client.SelectUsers()

	var remoteName string
	var chatMsg string
	color.Yellow("请输入要私聊的用户名(输入 exit 退出):")
	fmt.Scanln(&remoteName)
	if remoteName == "exit" {
		return
	}
	if remoteName == "" || remoteName == client.Name {
		color.Red("无效的用户名!")
		return
	}

	color.Green("开始与 %s 私聊... 💭", remoteName)
	for {
		color.Yellow("请输入消息内容(输入 exit 退出):")
		fmt.Scanln(&chatMsg)
		if chatMsg == "exit" {
			return
		}
		if len(chatMsg) != 0 {
			sendMsg := "to|" + remoteName + "|" + chatMsg + "\n"
			_, err := client.conn.Write([]byte(sendMsg))
			if err != nil {
				color.Red("发送失败: %v", err)
				break
			}
		}
	}
}

func (client *Client) PublicChat() {
	var msg string
	color.Green("进入群聊模式 💬")
	for {
		color.Yellow("请输入要发送的消息(输入 exit 退出):")
		fmt.Scanln(&msg)
		if msg == "exit" {
			break
		}
		if len(msg) != 0 {
			sendMsg := msg + "\n"
			_, err := client.conn.Write([]byte(sendMsg))
			if err != nil {
				color.Red("发送失败: %v", err)
				break
			}
		}
	}
}

func (client *Client) DealResponse() {
	// forever copy from conn to stdout
	// block until conn is closed
	io.Copy(os.Stdout, client.conn)
	// equivalent to:
	// for {
	// 	buf := make([]byte, 4096)
	// 	client.conn.Read(buf)
	// 	fmt.Println(buf)
	// }
}

var serverIp string
var serverPort int

func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "set serverIP(default: 127.0.0.1)")
	flag.IntVar(&serverPort, "port", 8888, "set serverPort(default: 8888)")
}

func main() {
	client := NewClient("127.0.0.1", 8888)
	if client == nil {
		color.Red("========== 连接失败 ❌ ==========")
		return
	}
	color.Green("========== 连接成功 ✅ ==========")

	// start a goroutine to handle response(receive message from server)
	go client.DealResponse()

	// main goroutine: send message to server(send message to server)
	client.Run()
}
